package com.ycd.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.ycd.domain.Product;
import com.ycd.domain.Result;
import com.ycd.domain.Store;
import com.ycd.fegins.ProductFeignClient;
import com.ycd.service.IStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/store")
public class StoreController {

    @Autowired
    private IStoreService storeService;

    @Autowired
    private ProductFeignClient productFeignClient;

    // 完成库存服务-store的保存接口成功
    @RequestMapping(value="/save", method = RequestMethod.POST)
    public Result register(@RequestBody Store store){
        storeService.save(store);
        return new Result();
    }

    // 使用openfegin组件-调用（store）商品服务进行添加
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public Result register(@RequestBody Product product){
        productFeignClient.add(product);
        return new Result();
    }


    /**
     * 对Product(商品服务)做熔断降级操作
     * @param id
     * @return
     */
    @GetMapping("/loadById/{id}")
    // 这里只做了fallback-当前类熔断降级操作
    @SentinelResource(value="product-loadById", fallback = "fuseDegradation" )
    public Product loadById(@PathVariable("id") Long id) {
        return productFeignClient.loadById(id);
    }

    /**
     * 启动库存服务store和商品服务product
     * 都启动正常访问到数据,关闭Product服务，返回错误信息，熔断降级
     */
    public Product fuseDegradation(@PathVariable("id") Long id, Throwable e){
        e.printStackTrace();
        return new Product(-1L, "熔断服务降级触发！", "服务不可用，请稍后重试！",1);
    }
}
